﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DataConsistency.UC
{
    public partial class Config : UserControl
    {
        public Config()
        {
            InitializeComponent();
        }
        // Set Path
        public string path = "C:\\\\cygwin\\\\usr\\\\local\\\\ns-allinone-2.31\\\\ns-2.31\\\\AppTest\\\\";
        public string kickban_path = "KichBan\\\\";
        public string DB_BS_path = "KichBan\\\\BS_data.txt";
        public string HLC_BS_path = "KichBan\\\\BS_HLC.txt";
        public string path_output = "KetQua\\\\";
        
        Para CPara = new Para();

        //==== Declare variables ==== //
        public string channel;
        public string radioPro;
        public string networkInter;
        public string macType;
        public string antene;
        public string interfaceQueue;
        public string linkLayer;
        public string routingPro;
        public int numOfNode;
        public int maxPacket;
        public int numOfBS = 1;
        public double stop = 7000;

        public int attri = 1;
        public int numberClient_Inf = 5;
        public double bandwidth_down = 100.0;
        public double bandwidth_up = 19.2;
        public int Energy = 1;
        public int bSize = 50;
        public int numOfBSData;
        public int ttl = 5;
        public int minOfDataItem;
        public int maxOfDataItem;
        public int numOfItemChange = 0;
        /// <summary>
        /// Cau truc Node cua MU
        /// </summary>
        public struct MUNode
        {
            public string id;
            public double x;
            public double y;
  
        };

        public struct DataItem
        {
            public int id;
            public string item;
            public string datetime;
            public int timetl;
            public int size;
        };

        List<MUNode> listOfNode = new List<MUNode>();
        List<DataItem> listOfDataItem = new List<DataItem>();
        
        List<List<int>> listMUNode = new List<List<int>>();
        List<List<int>> listHLC = new List<List<int>>();

        List<int> idCh = new List<int>();// List Items Changed

        public string content; // Bien content cua TCL


        /// <summary>
        /// Set variables
        /// </summary>
        public void SetVariables()
        {
            channel = "Channel/WirelessChannel";
            radioPro = "Propagation/TwoRayGround";
            networkInter = "Phy/WirelessPhy";
            macType = "Mac/802_11";
            antene = "Antenna/OmniAntenna";
            interfaceQueue = "Queue/DropTail/PriQueue";
            linkLayer = "LL";
            routingPro = "DSDV";
            numOfNode = int.Parse(cmbnumOfNode.Text.ToString());
            maxPacket = 50;
        }

        /// <summary>
        /// Thay doi tinh Readonly cua Grid view
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="status"></param>
        public void Grid_Status(DataGridView dgv, Boolean status)
        {
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                dgv.Columns[i].ReadOnly = status;
            }
        }

        /// <summary>
        /// Khoi tao user control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Config_Load(object sender, EventArgs e)
        {
            cmbnumOfNode.Value = 80;
            cmbnumOfData.Value = 1000;
        }

        /// <summary>
        /// Xuat cac ket qua ra file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            SetVariables();
            getNodePosition();

            // =============== Ghi file TCL ============================
            // Define
            content = content + "# Define options" + "\n";
            content =   content + "set val(chan)" + "\t\t" + channel + "\n" +
                        "set val(prop)" + "\t\t" + radioPro + "\n" +
                        "set val(netif)" + "\t\t" + networkInter + "\n" +
                        "set val(mac)" + "\t\t" + macType + "\n" +
                        "set val(ant)" + "\t\t" + antene + "\n" +
                        "set val(ifq)" + "\t\t" + interfaceQueue + "\n" +
                        "set val(ifqlen)" + "\t\t" + maxPacket + "\n" +
                        "set val(ll)" + "\t\t\t" + linkLayer + "\n" +
                        "set val(nn)" + "\t\t\t" + numOfNode + "\n" +
                        "set val(rp)" + "\t\t\t" + routingPro + "\n" +
                        "set numBS" + "\t\t\t" + numOfBS + "\n" +
                        "set val(stop)" + "\t\t" + String.Format("{0:0.0}", stop) + "\n\n";

            content = content + "#============================" + "\n\n" ;

            // Hieu chinh ban kinh Broadcast
            content = content + "# === Hieu chinh ban kinh ===" + "\n";
            content = content + "$val(netif) set CPThresh_ 10.0" + "\n" +
                                "$val(netif) set CSThresh_ \t 1.559e-11" + "\n" +
                                "$val(netif) set RXThresh_ \t 1.15126e-10" + "\n" +
                                "$val(netif) set Rb_ 2*1e6" + "\n" +
                                "$val(netif) set Pt_ 0.2818" + "\n" +
                                "$val(netif) set freq_ 914e+6" + "\n" +
                                "$val(netif) set L_ 1.0" + "\n\n";

            content = content + "#============================" + "\n\n";

            //Main program
            content = content + "#=== Main Program ===" + "\n";
            content = content + "set ns_ [new Simulator]" + "\n" + 
                                "set tracefd [open out.tr w]" + "\n" +
                                "$ns_ trace-all $tracefd"  + "\n\n" ;

            content = content + "#============================" + "\n\n";

            //Tao ranh gioi mo phong
            content = content + "#Tao ranh gioi mo phong" + "\n";
            content = content + "set topo [new Topography]" + "\n" +
                                "$topo load_flatgrid 1000 1000" + "\n\n";

            content = content + "#============================" + "\n\n";

            //Create-god doi tuong
            content = content + "#Create God doi tuong quan ly cac doi tuong ns-2" + "\n" +
                                "create-god [expr $val(nn) + $numBS]" + "\n" +
                                "set chan_1_ [new $val(chan)]" + "\n";

            content = content + "#============================" + "\n\n";

            // Cau hinh mobile node
            content = content + "#Tao cau hinh mobile node" + "\n" +
                                "Agent/Protoname set numberClient $val(nn)" + "\n" +
                                "Agent/Protoname set numberClient_Influence " + numberClient_Inf + "\n" +
                                "Agent/Protoname set bandwidth_down " + bandwidth_down + "\n" +
                                "Agent/Protoname set bandwidth_up " + bandwidth_up + "\n" +
                                "Agent/Protoname set Energy " + Energy + "\n" +
                                "Agent/Protoname set bSize " + bSize + "\n" + 
                                "$ns_ node-config -adhocRouting $val(rp) \\" + "\n" +
                                "\t\t\t\t -llType $val(ll) \\" + "\n" + 
                                "\t\t\t\t -macType $val(mac) \\" + "\n" +
                                "\t\t\t\t -ifqType $val(ifq) \\" + "\n" +
                                "\t\t\t\t -ifqLen $val(ifqlen) \\" + "\n" +
                                "\t\t\t\t -antType $val(ant) \\" + "\n" +
                                "\t\t\t\t -propType $val(prop) \\" + "\n" +
                                "\t\t\t\t -phyType $val(netif) \\" + "\n" +
                                "\t\t\t\t -topoInstance $topo  \\" + "\n" +
                                "\t\t\t\t -channelType $val(chan) \\" + "\n" +
                                "\t\t\t\t -wiredRouting OFF \\" + "\n" +
                                "\t\t\t\t -agentTrace ON  \\" + "\n" +
                                "\t\t\t\t -routerTrace ON \\" + "\n" +
                                "\t\t\t\t -macTrace OFF \\" + "\n" +
                                "\t\t\t\t -movementTrace OFF" + "\n\n";

            content = content + "#============================" + "\n\n";

            content = content + "#  Thiet lap BS va cac mobile node" + "\n" +
                                "set BS(0) [$ns_ node 0]" + "\n" +
                                "$BS(0) random-motion 0" + "\n" +
                                "set p_BS [new Agent/Protoname [$BS(0) node-addr]]" + "\n" +
                                "$ns_ attach-agent $BS(0) $p_BS" + "\n" +
                                "$p_BS setAttribute 100 " + attri + "\n" +
                                "$p_BS KhoiTaoDB_BS " + "\"" + path + DB_BS_path + "\"" + "\n" + 
                                "$p_BS KhoiTaoHLC_BS" + "\"" + path + HLC_BS_path + "\"" + "\n" +
                                "$p_BS pathOutPut " + "\"" + path + path_output + "\"" + "\n\n" ;

            content = content + "#============================" + "\n\n";

            content = content + "for {set i 1} {$i <= $val(nn) } {incr i} {" + "\n" +
                                "\t\t set node_($i) [$ns_ node $i]" + "\n" +
                                "\t\t $node_($i) random-motion 0" + "\n" +
                                "\t\t set p_($i) [new Agent/Protoname [$node_($i) node-addr]]" + "\n" +
                                "\t\t $ns_ attach-agent $node_($i) $p_($i)" + "\n" +
                                "\t\t $ns_ connect $p_($i) $p_BS" + "\n" +
                                "\t\t #Khoi tao gia tri: argv[1]: cacheSite; argv[2]:  Label" + "\n" +
                                "\t\t $p_($i) setAttribute 10 1" + "\n" +
                                "\t\t $p_($i) pathOutPut " + "\"" + path + path_output + "\"" + "\n" +
                                "\t\t #Khoi tao du lieu cho moi MU" + "\n" +
                                "\t\t set filename " + path + kickban_path + "MU" + "\n" +
                                "\t\t append filename $i" + "\n" +
                                "\t\t append filename " + "\"" + "_data.txt" + "\"" + "\n" +
                                "\t\t $p_($i) KhoiTaoLD_MU $filename" + "\n" +
                                "}" + "\n\n";                    

            content = content + "for {set i 1} {$i < $val(nn)} {incr i} {" + "\n" + 
		                        "\t\t set kq [expr $val(nn)-1]" + "\n" + 
		                        "\t\t if {$i == $kq} {" + "\n" + 
		                        "\t\t break" + "\n" + 
		                        "\t\t }" + "\n" +    
		                        "\t\t for {set j [expr $i +1]} {$j <= $val(nn)} {incr j} {" + "\n" + 
			                    "\t\t\t $ns_ connect $p_($i) $p_($j)" + "\n" +
		                        "}" + "\n\n";

            content = content + "#============================" + "\n\n";
            
            // Thiet lap toa do MU
            content = content + "# Thiet lap toa do cho cac mobile node trong khong gian 2 chieu" + "\n";
     
            for (int i = 0; i < listOfNode.Count; i++)
            {
                MUNode m = listOfNode[i];
                content = content + "$" + m.id + " set X_ " + String.Format("{0:0.0}", m.x) + "\n";
                content = content + "$" + m.id + " set Y_ " + String.Format("{0:0.0}", m.y) + "\n";
                content = content + "$" + m.id + " set Z_ 0.0 " + "\n\n";
            }
            content = content + "\n";
            content = content + "#============================" + "\n\n";

                // Run
            content = content + "for {set i 1} {$i <= $val(nn) } {incr i} {" + "\n" +
                                "\t $ns_ at $val(stop) " + "\"" + "$node_($i) reset" + "\"" + "\n" +
                                "\t $ns_ at $val(stop) " + "\"" + "$p_($i) StopTrace_Client" + "\"" + "\n" +
                                "}" + "\n" +
                                "$ns_ at $val(stop).0001 " + "\"" + "$BS(0) reset" + "\"" + "\n" +
                                "$ns_ at $val(stop).0001 " + "\"" + "$p_BS StopTrace" + "\"" + "\n" +
                                "$ns_ at $val(stop).0002 " + "\"" + "stop" + "\"" + "\n" +
                                "$ns_ at $val(stop).0003 " + "\"" + "puts \\" + "FINISH...\\" + "\"" + "; $ns_ halt" + "\"" + "\n" +
                                "proc stop {} {" + "\n" +
                                "}" + "\n" +
                                "puts" + "\"" + "Starting Simulation..." + "\"" + "\n" +
                                "$ns_ run" + "\n";  

            SaveFileDialog DialogSave = new SaveFileDialog();
            DialogSave.DefaultExt = "tcl";
            DialogSave.Filter = "TCL file (*.tcl)|*.tcl";
            DialogSave.AddExtension = false;
            DialogSave.RestoreDirectory = true;
            DialogSave.Title = "Where do you want to save the file?";
            DialogSave.InitialDirectory = @"C:/cygwin/usr/local/ns-allinone-2.31/ns-2.31";

            // Show the dialog and process the result
            if (DialogSave.ShowDialog() == DialogResult.OK)
            {
                string writeFile = DialogSave.FileName;  
                CPara.ClearFile(writeFile);
                CPara.WriteFile(writeFile, content);
               
            }
            DialogSave.Dispose();
            DialogSave = null;

            // =======================================


        }
        /// <summary>
        /// Bat su kien thay doi so node 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbnumOfNode_EditValueChanged(object sender, EventArgs e)
        {
            gridNodes.Rows.Clear();
            cmbMUNode.Properties.Items.Clear();
            numOfNode = (int)cmbnumOfNode.Value;

            Random rand = new Random(); // Khoi tao random
            
            //Duyet qua tung node
            for (int i = 0; i < numOfNode; i++)
            {                
                string id_item = "node_(" + (i + 1).ToString() + ")";
                double x = rand.Next(1, 1000);
                double y = rand.Next(1, 1000);

                gridNodes.Rows.Add();
                gridNodes.Rows[i].Cells[0].Value = id_item;
                gridNodes.Rows[i].Cells[1].Value = x;
                gridNodes.Rows[i].Cells[2].Value = y;
                cmbMUNode.Properties.Items.Add(id_item);              
            }
            
        }
        /// <summary>
        /// Lay vi tri cac node tren Grid View
        /// </summary>
        public void getNodePosition()
        {
            if (listOfNode != null)
            {
                listOfNode.Clear();
            }
            for (int i = 0; i < numOfNode; i++)
            {
                MUNode m = new MUNode();
                m.id = gridNodes.Rows[i].Cells[0].Value.ToString();
                m.x = double.Parse(gridNodes.Rows[i].Cells[1].Value.ToString());
                m.y = double.Parse(gridNodes.Rows[i].Cells[2].Value.ToString());

                listOfNode.Add(m);
            }
        }
        /// <summary>
        /// Khoi tao cac data item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInit_Click(object sender, EventArgs e)
        {
            if(btnInit.Text == "Initial Data")
            {
                btnInit.Text = "Change Data";
                MessageBox.Show("Data is initial.\nNow you can change it...");
                            
                // ====== BS_data =======
                GhiFileBS_MU();                
                // ==========================                               

            }
            else
            {               
                //Xac dinh so Item can Random de change them
                int num = int.Parse(cmbItemsChange.Value.ToString());
                int ItemsChange = num - numOfItemChange;
                numOfItemChange = num;// Gan lai so luong da change hien tai
                string IDChangeName = "BS_IDchange_" + num.ToString() + ".txt";                
                RandomItemsChange(ItemsChange, IDChangeName);

            }
            //----------------------------------
            
        }

        /// <summary>
        /// Ghi file BS_MU.txt
        /// </summary>
        public void GhiFileBS_MU()
        {
            string id;
            string id_data;
            string date_time;
            string ttl;
            string size;
            //MessageBox.Show(ran.ToString("dd/MM/yyyy hh:mm:ss"));
            string content = "";
            for (int i = 0; i < numOfBSData; i++)
            {
                id = gridBSData.Rows[i].Cells[0].Value.ToString();
                id_data = gridBSData.Rows[i].Cells[1].Value.ToString();
                date_time = gridBSData.Rows[i].Cells[2].Value.ToString();
                ttl = gridBSData.Rows[i].Cells[3].Value.ToString();
                size = gridBSData.Rows[i].Cells[4].Value.ToString();
                content = content + id + "-" + id_data + "-" + date_time + "-" + ttl + "-" + size + "\r\n";

            }
            CPara.WriteFile(path + DB_BS_path, content);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ItemsChange"></param>
        /// <param name="IDChangeName"></param>
        public void RandomItemsChange(int ItemsChange, string IDChangeName)
        {
            string IDChangeOut = "";
            Random randomIDChange = new Random();
            //Random ID change

            string currentTime = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
            currentTime = currentTime.Replace("-", "/");

            for (int c = 0; c < ItemsChange; c++)
            {
                int x = 1;
                do
                {
                    x = randomIDChange.Next(1, numOfBSData);
                }
                while (CheckInList(idCh, x) == true);
                // Items change
                string oldItem = gridBSData.Rows[x - 1].Cells[1].Value.ToString();
                string itemChange = oldItem.Remove(1, 1).ToString();
                //MessageBox.Show(x + " " + oldItem + " " + itemChange);
                gridBSData.Rows[x - 1].Cells[1].Value = itemChange;
                gridBSData.Rows[x - 1].Cells[2].Value = currentTime;
                idCh.Add(x);
            }

            for (int i = 0; i < idCh.Count; i++)
            {
                int id = idCh[i];
                DataItem dItem = listOfDataItem[id];

                // Tinh lai size 
                string rcont = id.ToString() + "-" + gridBSData.Rows[id - 1].Cells[1].Value.ToString() + "-" +
                            gridBSData.Rows[id - 1].Cells[3].Value.ToString() + "-" +
                            gridBSData.Rows[id - 1].Cells[2].Value.ToString() + "-";
                int size = rcont.Length + 2;
                //MessageBox.Show(rcont + " " + size.ToString());
                gridBSData.Rows[id - 1].Cells[4].Value = size;

                IDChangeOut = IDChangeOut + id.ToString() + "-" + gridBSData.Rows[id - 1].Cells[2].Value.ToString() 
                                + "-" + size.ToString() + "\r\n";
            }
            //MessageBox.Show(IDChangeOut);
            string IDChangePath = path + path_output + IDChangeName;
            MessageBox.Show("Random Id Change successful!");
            CPara.WriteFile(IDChangePath, IDChangeOut);

            // Ghi lai file BS_MU voi nhung thay doi 
            GhiFileBS_MU();
        }


        /// <summary>
        /// Kiem tra Id du lieu co trong list ko
        /// </summary>
        /// <param name="l"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool CheckInList(List<int> l, int t)
        {
            bool flag = false;
            for (int i = 0; i < l.Count; i++)
            {
                if (t == l[i])
                    flag = true;
            }
            return flag;
        }

        /// <summary>
        /// Bat su kien thay doi so luong du lieu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbnumOfData_EditValueChanged(object sender, EventArgs e)
        {
            gridBSData.Rows.Clear();
            // Random BS_Data
            numOfBSData = (int)cmbnumOfData.Value;
            Random gen = new Random();
            for (int i = 0; i < numOfBSData; i++)
            {
                int RowSize = 0;
                string id_data;
                id_data = "d0" + (i + 1).ToString();

                //Random date time
                DateTime from = new DateTime(2010, 1, 1);
                DateTime to = new DateTime(2011,1 , 1);
                int range = ((TimeSpan)(to - from)).Days;
                DateTime ran = from.AddDays(gen.Next(range));
                string date_time = ran.ToString("dd/MM/yyyy hh:mm:ss");
                date_time = date_time.Replace("-", "/");
                //MessageBox.Show(date_time);

                //Tinh size tung dong
                string rcont = (i + 1).ToString() + "-" + id_data.ToString() + "-" + date_time.ToString() + "-"
                                + ttl.ToString() + "-";
                RowSize = RowSize + rcont.Length + 2;

                // Dua len Gridview
                gridBSData.Rows.Add();
                gridBSData.Rows[i].Cells[0].Value = i + 1;
                gridBSData.Rows[i].Cells[1].Value = id_data;
                gridBSData.Rows[i].Cells[2].Value = date_time;
                gridBSData.Rows[i].Cells[3].Value = ttl;
                gridBSData.Rows[i].Cells[4].Value = RowSize;
 
                if (listOfDataItem == null)
                {
                    listOfDataItem.Clear();
                }
                else
                {
                    DataItem dItem = new DataItem();
                    dItem.id = i + 1;
                    dItem.item = id_data;
                    dItem.datetime = date_time;
                    dItem.timetl = ttl;
                    dItem.size = RowSize;
                    listOfDataItem.Add(dItem);                    
                }
            }         
        }

        private void cmbMUNode_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridMUData.Rows.Clear();// Clear Grid View

            int index = cmbMUNode.SelectedIndex;// Lay ra MU tuong ung duoc chon

            //MessageBox.Show(index.ToString());
            List<int> lID = listMUNode[index];
            
            for (int i = 0; i < lID.Count; i++)
            {
                int idItem = lID[i];// Lay tung don vi du lieu tuong ung voi MU
                DataItem dItem = listOfDataItem[idItem];
                gridMUData.Rows.Add();
                gridMUData.Rows[i].Cells[0].Value = dItem.id.ToString();
                gridMUData.Rows[i].Cells[1].Value = dItem.item.ToString();
                gridMUData.Rows[i].Cells[2].Value = dItem.datetime.ToString();
                gridMUData.Rows[i].Cells[3].Value = dItem.timetl.ToString();
                gridMUData.Rows[i].Cells[4].Value = dItem.size.ToString();

            }
            
        }        


        /// <summary>
        /// Random data item to MU
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRandomMU_Click(object sender, EventArgs e)
        {
            // ---------------- Random MU_Data
            // Random so id du lieu cho MU
            Random r = new Random();
            minOfDataItem = int.Parse(txtMin.Text.ToString());
            maxOfDataItem = int.Parse(txtMax.Text.ToString());            
            listMUNode.Clear();
            
            // Truong hop 
            if (minOfDataItem == maxOfDataItem)
            {
                for (int i = 0; i < numOfNode; i++)
                {
                    
                    List<int> id_MUData = new List<int>();

                    for (int j = 0; j < minOfDataItem; j++)
                    {
                        //Random id data 
                        int id_ran;
                        /*
                            int id_ran = r.Next(0, numOfBSData);

                            if (CheckInList(id_MUData, id_ran) == false)
                            {
                                id_MUData.Add(id_ran); // Add vao list
                            }
                        */ 
                        do
                        {
                            id_ran = r.Next(0, numOfBSData);
                        }
                        while (CheckInList(id_MUData, id_ran) == true);
                        id_MUData.Add(id_ran);

                    }

                    // Add items data vao list of Node
                    listMUNode.Add(id_MUData);
                    // Ghi file MU Data
                    string pth = path + kickban_path + "MU" + (i + 1).ToString() + "_data.txt";
                    string cont = "";
                    for (int k = 0; k < id_MUData.Count; k++)
                    {
                        int id_d = id_MUData[k];
                        cont = cont + gridBSData.Rows[id_d].Cells[0].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[1].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[2].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[3].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[4].Value.ToString() + "\r\n";
                    }
                    CPara.WriteFile(pth, cont);

                    //MessageBox.Show(cont);
                }
                // Create HLC
                // Duyet het cac don vi du lieu
                gridHLC.Rows.Clear();
                string HlcOutput = "";
                for (int i = 1; i <= numOfBSData; i++)
                {
                    gridHLC.Rows.Add();
                    gridHLC.Rows[i - 1].Cells[0].Value = i.ToString();
                    gridHLC.Rows[i - 1].Cells[1].Value = listOfDataItem[i - 1].item.ToString();
                    string cont = "";
                    List<int> lItems = new List<int>();
                    // Duyet tung MU trong list MU

                    for (int j = 0; j < listMUNode.Count; j++)
                    {
                        // Kiem tra co don vi du lieu i trong MU do ko
                        if (CheckInList(listMUNode[j], i - 1) == true)
                        {
                            // Add vao HLC
                            //listHLC[i - 1].Add(j);
                            if (lItems.Count == 0)
                            {
                                cont = cont + (j + 1).ToString();
                            }
                            else
                            {
                                cont = cont + "," + (j + 1).ToString();
                            }
                            lItems.Add(j + 1);
                            listHLC.Add(lItems);
                        }
                    }
                    gridHLC.Rows[i - 1].Cells[2].Value = cont;

                    if (lItems.Count != 0)
                    {
                        HlcOutput = HlcOutput + i.ToString() + "-" + cont + "\r\n";
                    }
                }
                string hlcFileName = path + kickban_path + "BS_HLC.txt";
                CPara.WriteFile(hlcFileName, HlcOutput);
                MessageBox.Show("MUs Data were randomized...");
            }
            else
            {
                for (int i = 0; i < numOfNode; i++)
                {
                    int num = r.Next(minOfDataItem, maxOfDataItem);// Random so luong data item

                    List<int> id_MUData = new List<int>();

                    for (int j = 0; j < num; j++)
                    {
                        //Random id data 
                        int id_ran = r.Next(0, numOfBSData);

                        if (CheckInList(id_MUData, id_ran) == false)
                        {
                            id_MUData.Add(id_ran); // Add vao list
                        }
                    }

                    // Add items data vao list of Node
                    listMUNode.Add(id_MUData);
                    // Ghi file MU Data
                    string pth = path + kickban_path + "MU" + (i + 1).ToString() + "_data.txt";
                    string cont = "";
                    for (int k = 0; k < id_MUData.Count; k++)
                    {
                        int id_d = id_MUData[k];
                        cont = cont + gridBSData.Rows[id_d].Cells[0].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[1].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[2].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[3].Value.ToString() + "-"
                            + gridBSData.Rows[id_d].Cells[4].Value.ToString() + "\r\n";
                    }
                    CPara.WriteFile(pth, cont);

                    //MessageBox.Show(cont);
                }
                // Create HLC
                // Duyet het cac don vi du lieu
                gridHLC.Rows.Clear();
                string HlcOutput = "";
                for (int i = 1; i <= numOfBSData; i++)
                {
                    gridHLC.Rows.Add();
                    gridHLC.Rows[i - 1].Cells[0].Value = i.ToString();
                    gridHLC.Rows[i - 1].Cells[1].Value = listOfDataItem[i - 1].item.ToString();
                    string cont = "";
                    List<int> lItems = new List<int>();
                    // Duyet tung MU trong list MU

                    for (int j = 0; j < listMUNode.Count; j++)
                    {
                        // Kiem tra co don vi du lieu i trong MU do ko
                        if (CheckInList(listMUNode[j], i - 1) == true)
                        {
                            // Add vao HLC
                            //listHLC[i - 1].Add(j);
                            if (lItems.Count == 0)
                            {
                                cont = cont + (j + 1).ToString();
                            }
                            else
                            {
                                cont = cont + "," + (j + 1).ToString();
                            }
                            lItems.Add(j + 1);
                            listHLC.Add(lItems);
                        }
                    }
                    gridHLC.Rows[i - 1].Cells[2].Value = cont;

                    if (lItems.Count != 0)
                    {
                        HlcOutput = HlcOutput + i.ToString() + "-" + cont + "\r\n";
                    }
                }
                string hlcFileName = path + kickban_path + "BS_HLC.txt";
                CPara.WriteFile(hlcFileName, HlcOutput);
                MessageBox.Show("MUs Data were randomized...");
            }

        }

    }
}
